﻿using System.Collections.Generic;
using Development.Tools;
using System.Threading;

namespace Development.Network.Msg
{
    /// <summary>
    /// msg queue
    /// </summary>
    public class MsgQueue
    {
        private Queue<MsgPacket> m_msgQueue = new Queue<MsgPacket>();
        private object m_lock = new object();
        private int m_count = 0;

        /// <summary>
        /// count of queue
        /// </summary>
        public int Count
        {
            get
            {
                return m_count;
            }
        }

        /// <summary>
        /// enter msg in queue
        /// </summary>
        /// <param name="msg"></param>
        public void EnQueue(MsgPacket msg)
        {
            lock (m_lock)
            {
                m_msgQueue.Enqueue(msg);
                Interlocked.Increment(ref m_count);
            }
        }


        /// <summary>
        /// get one msg from queue ,if the count is zero retun null
        /// </summary>
        /// <returns></returns>
        public MsgPacket DeQueue()
        {
            lock (m_lock)
            {
                if (m_msgQueue.Count > 0)
                {
                    MsgPacket msg = m_msgQueue.Dequeue();
                    Interlocked.Decrement(ref m_count);
                    return msg;
                }
                else
                {
                    return null;
                }
            }
        }
    }
}
